package com.weipai.education.service.impl;

//import com.sun.java.util.jar.pack.ConstantPool;
import com.weipai.education.dao.*;
import com.weipai.education.enums.PurchaseStatus;
import com.weipai.education.enums.RetCode;
import com.weipai.education.enums.UserFlag;
import com.weipai.education.enums.UserType;
import com.weipai.education.model.*;
import com.weipai.education.model.api.PageResult;
import com.weipai.education.model.api.Response;
import com.weipai.education.service.PurchaseService;
import com.weipai.education.utils.OrderNumberUtils;
import com.weipai.education.utils.SessionUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author: 曹朋飞
 * @Date: 2018/12/13 10:00
 */
@Service
public class PurchaseServiceImpl implements PurchaseService {

    @Autowired
    private PurchaseDao purchaseDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private InventoryDao inventoryDao;
    @Autowired
    private UserCategoryDao userCategoryDao;
    @Autowired
    private UserEarningsDao userEarningsDao;
    @Autowired
    private SessionUserUtil sessionUserUtil;
    @Autowired
    private ProductDao productDao;
    @Autowired
    private ProductCateDao productCateDao;
    @Autowired
    private SystemDao systemDao;


    @Override
    public Response save(Purchase purchase) {
        Response response = new Response();

        //从session中获取登录账号信息
        String receiveUserId = sessionUserUtil.getUser().getId().toString();
        User user = userDao.selectByPrimaryKey(receiveUserId);

        //获取user账号的开通人,如果为-1表示开通账号为总部
        Integer deliverUserId = user.getSuperiorId();

        if( Integer.valueOf(user.getType()) == Integer.valueOf(UserType.HQ_USER.getType())){
            response.setCode(RetCode.NO_BUY);
            return response;
        }
        if (null == deliverUserId ) {
            response.setCode(RetCode.NO_SUPERIOR);
            return response;
        }
        if(deliverUserId != -1){ //不是总部开通账号
            deliverUserId = user.getReferrerId();  
        }

        Inventory inventory=inventoryDao.getInventory(deliverUserId.toString(),purchase.getProductId().toString());
        if(inventory == null){
            response.setCode(RetCode.UNDER_STOCK);
            return response;
        }
        if (inventory.getStock()<purchase.getProductNumber()){
            response.setCode(RetCode.UNDER_STOCK);
            return response;
        }

        purchase.setPurchaseNumber(OrderNumberUtils.outTradeNo());
        purchase.setReceiveUserId(Integer.parseInt(receiveUserId)).setDeliverUserId(deliverUserId).setStatus(0);
        purchaseDao.insert(purchase);

        //添加消息通知记录
        Message message = new Message();
        message.setUserId(user.getId()).setRecommendId(user.getSuperiorId()).setContent("您推荐的加盟商["+user.getNickname()+"]下单了").setType(2).setSign(0);
        systemDao.insertMsg(message);

        response.setCode(RetCode.SUCCESS);
        return response;
    }

    @Override
    public Response list(Integer page, Integer size, String startTime, String endTime, String key,
                         String type, String userId, String status) {

        User user = userDao.selectByPrimaryKey(userId);

        //如果账号为总部账号则查询总部所有的发货单
        if (user.getType() == UserType.HQ_USER.getType()) {
            type = null;
            userId = "-1";
        }

        Response response = new Response();
        Integer start = (page - 1) * size;
        List<Map<String, Object>> purchases = purchaseDao.list(start, size, startTime, endTime, key, userId, type, status);
        Integer totalNum = purchaseDao.listAmount(startTime, endTime, key, userId, type, status);
        PageResult<Map<String, Object>> pageList = new PageResult<>(purchases, page, size, totalNum);
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response changeStatus(String id, String goodsBarCodes, String productId, String dhl, String expressNumber, Integer isHeadset, Integer productNumber) {
        Response response = new Response();
        Purchase purchase = purchaseDao.selectByPrimaryKey(id);
        if (null == purchase) {
            response.setCode(RetCode.NOT_DATA);
            return response;
        }
        if (PurchaseStatus.HAVE_OUTBOUND.getType() == purchase.getStatus()) {
            response.setCode(RetCode.PURCHASE_HAVE_OUTBOUND);
            return response;
        }

        //从session中获取账号
        String userId = sessionUserUtil.getUser().getId().toString(); //自己的id
        String tempUser = userId;
        User user = userDao.selectByPrimaryKey(userId); //自己的信息
        if (user.getType() == UserType.HQ_USER.getType()) {
            tempUser = "-1";
        }
        Integer totalNumber;
        List<Integer> inventoryDetailId = new ArrayList<>();
        List<Map<String,Integer>> inventoryDetailInfo = new ArrayList<>();
//        判断是否需要条码  ,Integer isHeadset,Integer productNumber
        Inventory inventory = inventoryDao.getInventory(tempUser, productId);

        if (isHeadset == 1) { //需要条码
            String[] fields = goodsBarCodes.split("\n");
            totalNumber = fields.length;

            if (inventory == null) {
                response.setCode(RetCode.NOT_FIND);
                return response;
            }
            if (inventory.getStock() < totalNumber) {
                response.setCode(RetCode.UNDER_STOCK);
                return response;
            }

            for (String goodsBarCode : fields) {
                //根据userId和goodsBarCode查询此账户下是否有这个商品
                InventoryDetail inventoryDetail = inventoryDao.getInventoryDetail(tempUser, productId, goodsBarCode);
                if (null == inventoryDetail) {
                    response.setCode(RetCode.NOT_DATA);
                    response.put("goodsBarCode", "未找到[" + goodsBarCode + "]商品");
                    return response;
                }
                Map<String,Integer> tempMap = new HashMap<>();
                tempMap.put("isPrice",inventoryDetail.getIsPrice());
                tempMap.put("isDamage",inventoryDetail.getIsDamage());
                inventoryDetailInfo.add(tempMap);
                inventoryDetailId.add(inventoryDetail.getId());
            }

            for (String goodsBarCode : fields) {
                PurchaseDetail purchaseDetail = new PurchaseDetail();
                purchaseDetail.setGoodsBarCode(goodsBarCode).setPurchaseNumber(purchase.getPurchaseNumber());
                purchaseDao.insertProductDetail(purchaseDetail);
            }

            purchase.setStatus(PurchaseStatus.HAVE_OUTBOUND.getType()).setDhl(dhl).setExpressNumber(expressNumber).setDeliveryTime(new Date());
            purchaseDao.updateByPrimaryKeySelective(purchase);

            //减库存
            inventory.setStock(inventory.getStock() - fields.length);
            inventoryDao.updateByPrimaryKeySelective(inventory);

            //fields的商品从我的推荐人库中删除
            inventoryDao.batchDeleteInventoryDetailById(inventoryDetailId);

            //出库记录
            InventoryOut out = new InventoryOut();
            String outOrderNumber = OrderNumberUtils.outTradeNo();
            out.setPurchaseNumber(purchase.getPurchaseNumber()).setOutOrderNumber(outOrderNumber)
                    .setDeliverUserId(Integer.parseInt(tempUser)).setProductId(Integer.parseInt(productId))
                    .setProductNumber(fields.length).setReceiveUserId(purchase.getReceiveUserId()).setStatus(0);
            inventoryDao.saveInventoryOut(out);

            //出库记录明细
            for (int i = 0; i <= fields.length - 1; i++) {
                InventoryOutDetail inventoryOutDetail = new InventoryOutDetail();
                inventoryOutDetail.setOutOrderNumber(outOrderNumber).setGoodsBarCode(fields[i]).setIsDamage(inventoryDetailInfo.get(i).get("isDamage")).setIsPrice(inventoryDetailInfo.get(i).get("isPrice"));
                inventoryDao.saveInventoryOutDetail(inventoryOutDetail);
            }
        } else {
            totalNumber = productNumber;

            if (inventory == null) {
                response.setCode(RetCode.NOT_FIND);
                return response;
            }
            if (inventory.getStock() < totalNumber) {
                response.setCode(RetCode.UNDER_STOCK);
                return response;
            }
            //当前商品id  productId userId
            //这里获取要删除的id
            List<Map<String, Integer>> product = inventoryDao.selectDetailPeoduct(Integer.valueOf(productId), Integer.valueOf(tempUser), totalNumber);

            if (!product.isEmpty()) {
                for (Map<String, Integer> map : product) {
                    inventoryDetailId.add(map.get("id"));
                    Map<String,Integer> tempMap = new HashMap<>();
                    tempMap.put("isPrice",map.get("is_price"));
                    tempMap.put("isDamage",map.get("is_damage"));
                    inventoryDetailInfo.add(tempMap);
                }
            }
            inventoryDao.batchDeleteInventoryDetailById(inventoryDetailId);
            //改变状态
            purchase.setStatus(PurchaseStatus.HAVE_OUTBOUND.getType()).setDhl(dhl).setExpressNumber(expressNumber).setDeliveryTime(new Date());
            purchaseDao.updateByPrimaryKeySelective(purchase);

            //减库存
            inventory.setStock(inventory.getStock() - totalNumber);
            inventoryDao.updateByPrimaryKeySelective(inventory);
            //出库记录
            InventoryOut out = new InventoryOut();
            String outOrderNumber = OrderNumberUtils.outTradeNo();
            out.setPurchaseNumber(purchase.getPurchaseNumber()).setOutOrderNumber(outOrderNumber)
                    .setDeliverUserId(Integer.parseInt(tempUser)).setProductId(Integer.parseInt(productId))
                    .setProductNumber(totalNumber).setReceiveUserId(purchase.getReceiveUserId()).setStatus(0);
            inventoryDao.saveInventoryOut(out);

            //出库记录明细
            for (int i = 0; i <= totalNumber - 1; i++) {
                InventoryOutDetail inventoryOutDetail = new InventoryOutDetail();
                inventoryOutDetail.setOutOrderNumber(outOrderNumber).setGoodsBarCode("").setIsDamage(inventoryDetailInfo.get(i).get("isDamage")).setIsPrice(inventoryDetailInfo.get(i).get("isPrice"));
                inventoryDao.saveInventoryOutDetail(inventoryOutDetail);
            }
        }
        //如果user为总部账号的话，进行拿货分润
        if (user.getType() == UserType.HQ_USER.getType()) {
            //产品销量
            Product product = productDao.selectByPrimaryKey(productId);
            product.setSoldOut(product.getSoldOut() + totalNumber);
            productDao.updateProduct(product);
        }
        //接收人信息，即发单人的信息，判断发单人的状态
        //此采购订单的发起人
        User receiveUser = userDao.selectByPrimaryKey(Integer.toString(purchase.getReceiveUserId()));
        if(receiveUser.getSuperiorId() != -1){  //-1表示上级是后台账号 发单的人的上级不是平台账号
            //发单人的推荐人
            User referrerUser = user; //推荐人的信息 即当前账号

            //推荐人总部账号，是总部直接开通的，不走分润
            if (referrerUser.getType() == UserType.SELL_USER.getType()) {
                if(isHeadset == 1){
                    //推荐后期拿货奖励
                    recommendGoodsReward(receiveUser, purchase.getPurchaseNumber());

                    //区域 后期拿货奖励
                    areaGoodsReward(receiveUser, purchase.getPurchaseNumber());
                }

            }
//            User referrerUser = userDao.selectByPrimaryKey(Integer.toString(receiveUser.getReferrerId()));
        }
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    /**
     * 区域 后期拿货奖励
     *
     * @param receiveUser:拿货人
     * @param purchaseNumber：采购订单号
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void areaGoodsReward(User receiveUser, String purchaseNumber) {

        for (int i = 2; i <= 3; i++) {
            //查询我所在区域上面的代理
            User userSuperior = userDao.getCityCountyUser(receiveUser.getProvince() ,receiveUser.getCity(), receiveUser.getCounty(), i);

            if(userSuperior != null){
                if(userSuperior.getType() ==  UserType.SELL_USER.getType()){
//我的推荐人类别
                    UserCategory referrerUserCate = userCategoryDao.selectByPrimaryKey(Integer.toString(userSuperior.getUserCateId()));

                    //我上级的提成比例
                    BigDecimal areaGoodsReward = referrerUserCate.getAreaGoodsReward();

                    //计算上级应得的推荐奖
                    userSuperior.setGoodsReward(userSuperior.getGoodsReward().add(areaGoodsReward));

                    userDao.updateByPrimaryKeySelective(userSuperior);

                    addMessage(receiveUser ,areaGoodsReward,userSuperior.getId());
                    //奖金记录
                    saveUserEarnings(userSuperior.getId(), areaGoodsReward, 4, receiveUser.getId(), purchaseNumber);
                }
            }
        }
    }

    /**
     * 推荐后期拿货奖励
     *
     * @param receiveUser:拿货人
     * @param purchaseNumber：采购订单号
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void recommendGoodsReward(User receiveUser, String purchaseNumber) {

        //我的推荐人
        User referrerUser = userDao.selectByPrimaryKey(Integer.toString(receiveUser.getReferrerId()));

        if (null != referrerUser) {
            //我的推荐人类别
            UserCategory referrerUserCate = userCategoryDao.selectByPrimaryKey(Integer.toString(referrerUser.getUserCateId()));

            BigDecimal goodsReward = referrerUserCate.getGoodsReward();
            referrerUser.setGoodsReward(referrerUser.getGoodsReward().add(goodsReward));
            userDao.updateByPrimaryKeySelective(referrerUser);

            addMessage(receiveUser,goodsReward,referrerUser.getId());
            //奖金记录
            saveUserEarnings(referrerUser.getId(), goodsReward, 2, receiveUser.getId(), purchaseNumber);
        }

    }

    /**
     * 奖金记录
     *
     * @param userId：得奖人id
     * @param rewardPrice：奖金
     * @param type：1推荐奖，2拿货奖
     * @param offerUserId：新人
     */
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public void saveUserEarnings(Integer userId, BigDecimal rewardPrice, Integer type, Integer offerUserId, String purchaseNumber) {
        UserEarnings earnings = new UserEarnings();
        earnings.setUserId(userId).setRewardPrice(rewardPrice).setType(type)
                .setOfferUserId(offerUserId).setPurchaseNumber(purchaseNumber);
        userEarningsDao.insert(earnings);
    }
    @Override
    /**
     * user 被推荐人的信息
     * price 分成的钱
     * userId 推荐人的id
     */
    public void addMessage(User user,BigDecimal price,Integer userId ){
        //添加消息通知记录
        Message message = new Message();
        message.setUserId(user.getId()).setRecommendId(userId).setContent("您推荐的[" + user.getNickname() + "]下单，成功获得奖励"+ price+"元，可前往【我的收益】查看").setType(3).setSign(0);
        systemDao.insertMsg(message);
    }
    @Override
    public Response getGoodsBarCodeByPurchaseNumber(String purchaseNumber) {
        Response response = new Response();
        List<PurchaseDetail> purchaseDetails = purchaseDao.getGoodsBarCodeByPurchaseNumber(purchaseNumber);
        if (!purchaseDetails.isEmpty()) {
            response.setData(purchaseDetails);
            response.setCode(RetCode.SUCCESS);
        } else {
            response.setCode(RetCode.NOT_DATA);
        }
        return response;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response inventoryInSave(InventoryIn inventoryIn, String goodsBarCodes) {
        Response response = new Response();

        //从session中获取账号
        String userId = sessionUserUtil.getUser().getId().toString();

        Purchase purchase = purchaseDao.getPurchaseByPurchaseNumber(inventoryIn.getPurchaseNumber());
        if (null == purchase) {
            response.setCode(RetCode.NOT_DATA);
            return response;
        }
        if (PurchaseStatus.HAVE_INBOUND.getType() == purchase.getStatus()) {
            response.setCode(RetCode.PURCHASE_HAVE_INBOUND);
            return response;
        }
        List<Map<String,Object>> inventoryDetailInfo = new ArrayList<>();
        String[] fields = goodsBarCodes.split("\n");
        for (String goodsBarCode : fields) {

            //根据purchaseNumber和goodsBarCode查询此进货单的出库订单详情中是否有此商品
            Map<String,Object> purchaseDetail = purchaseDao.getPurchaseDetail(inventoryIn.getPurchaseNumber(), goodsBarCode);
            if (null == purchaseDetail || purchaseDetail.isEmpty()) {
                response.setCode(RetCode.NOT_DATA);
                response.put("goodsBarCode", "未找到[" + goodsBarCode + "]商品");
                return response;
            }
            Map<String,Object> tempMap = new HashMap<>();
            tempMap.put("isPrice",purchaseDetail.get("is_price"));
            tempMap.put("isDamage",purchaseDetail.get("is_damage"));
            inventoryDetailInfo.add(tempMap);
        }

        //入库记录
        String inOrderNumber = OrderNumberUtils.outTradeNo();
        inventoryIn.setInOrderNumber(inOrderNumber).setDeliverUserId(purchase.getDeliverUserId()).setReceiveUserId(purchase.getReceiveUserId())
                .setStatus(0);
        inventoryDao.saveInventoryIn(inventoryIn);

        //更改进货单状态
        purchase.setStatus(PurchaseStatus.HAVE_INBOUND.getType());
        purchaseDao.updateByPrimaryKeySelective(purchase);

        Inventory inventory = inventoryDao.getInventory(userId, Integer.toString(inventoryIn.getProductId()));
        if (null != inventory) {
            //加库存
            inventory.setStock(inventory.getStock() + fields.length);
            inventoryDao.updateByPrimaryKeySelective(inventory);
        } else {
            Inventory inventory1 = new Inventory();
            inventory1.setUserId(Integer.parseInt(userId)).setProductId(inventoryIn.getProductId())
                    .setStock(fields.length);
            inventoryDao.saveInventory(inventory1);
        }

        for (int i = 0; i <= fields.length - 1; i++) {

            //入库记录明细
            InventoryInDetail inventoryInDetail = new InventoryInDetail();
            inventoryInDetail.setInOrderNumber(inOrderNumber).setGoodsBarCode(fields[i]).setIsDamage((int)inventoryDetailInfo.get(i).get("isDamage")).setIsPrice((int)inventoryDetailInfo.get(i).get("isPrice"));
            inventoryDao.saveInventoryInDetail(inventoryInDetail);

            //库存明细
            InventoryDetail inventoryDetail = new InventoryDetail();
            inventoryDetail.setGoodsBarCode(fields[i]).setProductId(inventoryIn.getProductId())
                    .setUserId(Integer.parseInt(userId)).setIsDamage((int)inventoryDetailInfo.get(i).get("isDamage")).setIsPrice((int)inventoryDetailInfo.get(i).get("isPrice"));
            inventoryDao.saveInventoryDetail(inventoryDetail);
        }

        response.setCode(RetCode.SUCCESS);
        return response;

    }

    @Override
    public Response getPurchaseInfo(String purchaseNumber) {
        Response response = new Response();
        Map<String, Object> purchaseInfo = purchaseDao.getPurchaseInfo(purchaseNumber);
        List<PurchaseDetail> purchaseDetails = purchaseDao.getGoodsBarCodeByPurchaseNumber(purchaseNumber);
        if (purchaseInfo != null) {
            response.setCode(RetCode.SUCCESS);
            response.put("purchase", purchaseInfo);
            response.put("goodsBarNumber", purchaseDetails);
        } else {
            response.setCode(RetCode.NOT_DATA);
        }
        return response;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response headquartersInventoryInSave(String productId, String goodsBarCodes,
                                                String isPrice, String isDamage, Integer productNumber, String spuNumber, String name, Integer isHeadset) {
        Response response = new Response();

        //从session中获取账号
        String userId = sessionUserUtil.getUser().getId().toString();
        User user = userDao.selectByPrimaryKey(userId);
        if (user.getType() == UserType.SELL_USER.getType()) {
            response.setCode(RetCode.PERMISSION_DENIED);
            return response;
        }
        Integer goodsNumber = 0;
        if (isHeadset == 1) { //如果输入了条码
            if(goodsBarCodes == null){
                response.setCode(RetCode.NO_GOODSBAR);
                return response;
            }
            //查看货号中是否有此条形编码
            Response response1 = purchaseDao.verifyGoodsBarCodes(productId, goodsBarCodes);
            if (response1.getCode() == 401) {
                return response1;
            }

            //验证此条形码是否已使用
            Response response2 = purchaseDao.verifyGoodsBarCodesIsUse(productId, goodsBarCodes);
            if (response2.getCode() == 401) {
                return response2;
            }
            String[] fields = goodsBarCodes.split("\n");
            goodsNumber = fields.length;
        } else {
            //验证是否还有库存
            goodsNumber = productNumber;
        }

        //入库记录
        InventoryIn in = new InventoryIn();
        String inOrderNumber = OrderNumberUtils.outTradeNo();
        in.setPurchaseNumber("-1").setInOrderNumber(inOrderNumber)
                .setDeliverUserId(-1).setProductId(Integer.parseInt(productId))
                .setProductNumber(goodsNumber).setReceiveUserId(-1).setStatus(0);
        inventoryDao.saveInventoryIn(in);

        if (isHeadset == 1) {
            String[] fields = goodsBarCodes.split("\n");
            //加库存
            Inventory inventory = inventoryDao.getInventory("-1", productId);
            inventory.setStock(inventory.getStock() + fields.length);
            inventoryDao.updateByPrimaryKeySelective(inventory);

            for (int i = 0; i <= fields.length - 1; i++) {
                //入库记录明细
                InventoryInDetail inventoryInDetail = new InventoryInDetail();
                inventoryInDetail.setInOrderNumber(inOrderNumber).setGoodsBarCode(fields[i]).setIsDamage(Integer.valueOf(isDamage)).setIsPrice(Integer.valueOf(isPrice));
                inventoryDao.saveInventoryInDetail(inventoryInDetail);

                //库存明细
                InventoryDetail inventoryDetail = new InventoryDetail();
                inventoryDetail.setGoodsBarCode(fields[i]).setProductId(Integer.parseInt(productId)).setUserId(-1).setIsDamage(Integer.valueOf(isDamage)).setIsPrice(Integer.valueOf(isPrice));
                inventoryDao.saveInventoryDetail(inventoryDetail);

                //更新商品属性  生成条码的时候添加的商品详情（属性）
                productDao.updateProductGoods(fields[i], 1, isPrice, isDamage);

                //删除多余的货号
            }
        } else {
            //加库存
            Inventory inventory = inventoryDao.getInventory("-1", productId);
            inventory.setStock(inventory.getStock() + goodsNumber);
            inventoryDao.updateByPrimaryKeySelective(inventory);

            for (int i = 0; i < goodsNumber; i++) {
                //入库记录明细
                InventoryInDetail inventoryInDetail = new InventoryInDetail();
                inventoryInDetail.setInOrderNumber(inOrderNumber).setGoodsBarCode("").setIsDamage(Integer.valueOf(isDamage)).setIsPrice(Integer.valueOf(isPrice));
                inventoryDao.saveInventoryInDetail(inventoryInDetail);

                //库存明细
                InventoryDetail inventoryDetail = new InventoryDetail();
                inventoryDetail.setGoodsBarCode("").setProductId(Integer.parseInt(productId))
                        .setUserId(-1).setIsDamage(Integer.valueOf(isDamage)).setIsPrice(Integer.valueOf(isPrice));
                inventoryDao.saveInventoryDetail(inventoryDetail);
            }
        }

        response.setCode(RetCode.SUCCESS);
        return response;
    }

    @Override
    public Response cityLevelList(Integer page, Integer size, String startTime, String endTime, String key) {
        Response response = new Response();

        //从session中获取账号
        String userId = sessionUserUtil.getUser().getId().toString();
        User user = userDao.selectByPrimaryKey(userId);

        if (user.getFlag() != UserFlag.THE_MUNICIPAL_AGENTS.getType()) {
            response.setCode(RetCode.PERMISSION_DENIED);
            return response;
        }

        List<Map<String, Object>> userList = userDao.getUserByAddressAndFlag(user.getProvince(), user.getCity(),
                UserFlag.DISTRICT_LEVEL_AGENTS.getType(), UserFlag.FLAGSHIP_LEVEL_AGENTS.getType());

        List<Integer> idList = new ArrayList<>();
        for (Map<String, Object> map : userList) {
            idList.add(Integer.parseInt(map.get("id").toString()));
        }

        //根据查询出的id再次查询所有的采购订单
        Integer start = (page - 1) * size;
        List<Map<String, Object>> purchases = purchaseDao.cityLevelList(start, size, startTime, endTime, key, idList);
        Integer totalNum = purchaseDao.cityLevelListAmount(startTime, endTime, key, idList);
        PageResult<Map<String, Object>> pageList = new PageResult<>(purchases, page, size, totalNum);
        response.setCode(RetCode.SUCCESS);
        response.put("pageList", pageList);
        return response;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Response inventoryInSavebyNobarcode(InventoryIn inventoryIn, Integer productNumber, String productName,String inOrderNumber,String isheadset) {

        Response response = new Response();

        //从session中获取账号
        String userId = sessionUserUtil.getUser().getId().toString();

        if (Integer.valueOf(isheadset) == 1) {
            response.setCode(RetCode.HEADSET);
            return response;
        }

        //入库产品的数量
        Purchase purchase = purchaseDao.getPurchaseByPurchaseNumber(inventoryIn.getPurchaseNumber());
        if (null == purchase) {
            response.setCode(RetCode.NOT_DATA);
            return response;
        }
        if (PurchaseStatus.HAVE_INBOUND.getType() == purchase.getStatus()) {
            response.setCode(RetCode.PURCHASE_HAVE_INBOUND);
            return response;
        }
        Inventory inventory = new Inventory();

        //根据productName查询此进货单的出库订单详情中是否有此商品
        /* PurchaseDetail purchaseDetail =productDao.getProductById(productName);*/
  /*        Product product=productDao.getProductById(productName);
        if (null == product) {
            response.setCode(RetCode.NOT_DATA);
            response.put("productName", "未找到[" + productName + "]商品");

            return response;
        }*/
        //入库记录
        inOrderNumber = OrderNumberUtils.outTradeNo();
        inventoryIn.setInOrderNumber(inOrderNumber).setDeliverUserId(purchase.getDeliverUserId()).setReceiveUserId(purchase.getReceiveUserId())
                .setStatus(0);
        inventoryDao.saveInventoryIn(inventoryIn);

        //更改进货单状态
        purchase.setStatus(PurchaseStatus.HAVE_INBOUND.getType());
        purchaseDao.updateByPrimaryKeySelective(purchase);

        inventory = inventoryDao.getInventory(userId, Integer.toString(inventoryIn.getProductId()));
        if (null != inventory) {
            //加库存
            inventory.setStock(inventory.getStock() + productNumber);
            inventoryDao.updateByPrimaryKeySelective(inventory);
        } else {
            Inventory inventory1 = new Inventory();
            inventory1.setUserId(Integer.parseInt(userId)).setProductId(inventoryIn.getProductId())
                    .setStock(productNumber);
            inventoryDao.saveInventory(inventory1);
        }

        Integer productNumber1= purchase.getProductNumber();

        //查询产品的id


       /* ProductCate productCate = productCateDao.selectByPrimaryKey(inventory.getProductId().toString());
        Integer id= productCate.getId();*/




        /*Inventory inventory1=inventoryDao.getInventory(userId, String.valueOf(id));
        InventoryDetail inventoryOutDetail=inventoryDao.getInventoryDetail(userId, String.valueOf(id),"");*/
       /* InventoryInDetail inventoryOutDetail=inventoryDao.getInventoryOutDetail(inOrderNumber,"");*/
     //  InventoryInDetail inventoryOut= inventoryDao.getInventoryOutDetailByisPrice(inventoryIn.getPurchaseNumber());



        /*InventoryInDetail inventoryOutDetail=inventoryDao.getInventoryOutDetailByisDamage(inventoryOut.getInOrderNumber());

        inventoryOutDetail.getIsPrice();
        inventoryOutDetail.getIsDamage();
        Integer isPrice1=inventoryOutDetail.getIsPrice();
        Integer isDamage1=inventoryOutDetail.getIsDamage();*/

        //查询商品的isDamage，isPrice信息
//        InventoryDetail checkinventory = inventoryDao.getInventoryDetail(Integer.toString(purchase.getDeliverUserId()), Integer.toString(inventoryIn.getProductId()),null);
        InventoryOutDetail checkinventory = inventoryDao.getInventoryOutDetail(purchase.getPurchaseNumber(),Integer.toString(purchase.getReceiveUserId()), Integer.toString(inventoryIn.getProductId()));


        for (int i = 0; i <productNumber1 ; i++) {
            //入库记录明细

            InventoryInDetail inventoryInDetail = new InventoryInDetail();
            inventoryInDetail.setInOrderNumber(inOrderNumber).setGoodsBarCode("").setIsDamage(checkinventory.getIsDamage()).setIsPrice(checkinventory.getIsPrice());
            inventoryDao.saveInventoryInDetail(inventoryInDetail);

            //库存明细
            InventoryDetail inventoryDetail = new InventoryDetail();
            inventoryDetail.setProductId(inventoryIn.getProductId())
                    .setUserId(Integer.parseInt(userId)).setGoodsBarCode("").setIsDamage(checkinventory.getIsDamage()).setIsPrice(checkinventory.getIsPrice());
            inventoryDao.saveInventoryDetail(inventoryDetail);

        }
        response.setCode(RetCode.SUCCESS);
        return response;
    }

    @Override
    public Response searchOrderByOrderNumber(String OrderNumber, String type, Integer userId) {
        Response response = new Response();
        User user = userDao.selectByPrimaryKey(userId.toString());
        //如果账号为总部账号则查询总部所有的发货单
        if (user.getType() == UserType.HQ_USER.getType()) {
            type = null;
            userId = -1;
        }
        Map<String, Object> orderInfo = purchaseDao.searchOrderByOrderNumber(OrderNumber, userId);
        if (orderInfo == null) {
            response.setCode(RetCode.NOT_FIND_ORDERNUMBER);
            return response;
        }
        List<Map<String, Object>> goodsBarList = purchaseDao.getAllGoodsBar(OrderNumber);
        response.setCode(RetCode.SUCCESS);
        response.put("data", orderInfo);
        response.put("goodsbar", goodsBarList);
        return response;
    }

    @Override
    public Response saveOrder(@NotBlank(message = "产品id不能为空") String productId, Integer priductId, Purchase purchase) {

        Response response = new Response();

        //从session中获取登录账号信息
        String receiveUserId = sessionUserUtil.getUser().getId().toString();
        User user = userDao.selectByPrimaryKey(receiveUserId);

        //获取user账号的开通人,如果为-1表示开通账号为总部  这里获取的是我的推荐人
//        Integer deliverUserId = user.getSuperiorId();
        Integer deliverUserId = user.getReferrerId();
        if (null == deliverUserId) {
            response.setCode(RetCode.NO_SUPERIOR);
            return response;
        }

        //查询推荐人的库存
        Integer purchase1 = purchase.getDeliverUserId();
        Inventory inventory = inventoryDao.getInventory(purchase1.toString(), productId);

        if (inventory.getStock() < purchase.getProductNumber()) {
            response.setCode(RetCode.UNDER_STOCK);
            return response;
        }


        inventory.setStock(inventory.getStock());
        inventoryDao.updateByPrimaryKeySelective(inventory);

      /*  if (null != product) {
            for (Map<String, Integer> map : product) {
                inventoryDetailId.add(map.get("id"));
            }
        }

        //fields的商品从我的推荐人库中删除
        inventoryDao.batchDeleteInventoryDetailById(inventoryDetailId);*/


        //入库记录
        InventoryIn inventoryIn = new InventoryIn();
        String inOrderNumber = OrderNumberUtils.outTradeNo();
        inventoryIn.setInOrderNumber(inOrderNumber).setDeliverUserId(purchase.getDeliverUserId()).setReceiveUserId(purchase.getReceiveUserId())
                .setStatus(0);
        inventoryDao.saveInventoryIn(inventoryIn);

        //更改进货单状态
        purchase.setStatus(PurchaseStatus.HAVE_INBOUND.getType());
        purchaseDao.updateByPrimaryKeySelective(purchase);

        inventory = inventoryDao.getInventory(receiveUserId, Integer.toString(inventoryIn.getProductId()));
        if (null != inventory) {
            //加库存
            inventory.setStock(inventory.getStock());
            inventoryDao.updateByPrimaryKeySelective(inventory);
        } else {
            Inventory inventory1 = new Inventory();
            inventory1.setUserId(Integer.parseInt(receiveUserId)).setProductId(inventoryIn.getProductId());
            inventoryDao.saveInventory(inventory1);
        }


        //入库记录明细
        InventoryInDetail inventoryInDetail = new InventoryInDetail();
        inventoryInDetail.setInOrderNumber(inOrderNumber);
        inventoryDao.saveInventoryInDetail(inventoryInDetail);

        //库存明细
        InventoryDetail inventoryDetail = new InventoryDetail();
        inventoryDetail.setProductId(inventoryIn.getProductId())
                .setUserId(Integer.parseInt(receiveUserId));
        inventoryDao.saveInventoryDetail(inventoryDetail);

        response.setCode(RetCode.SUCCESS);
        return response;

    }
}
